<template>
	<view class="page">
		<u-navbar leftText="返回" title="" :placeholder="true" id="navbar">
			<view class="closeImg" slot="left">
				<image src="/static/index/cross-mark.png" mode="" @click="goBack()"></image>
				<view class="search-box" @click="showCommonSelectCity = true">
					<view class="placeholder-content">
						请输入城市名（如：北京市/北京/bj/beijing）
					</view>
					<view class="icon">
						<u-icon name="search" color="rgba(77, 77, 86, 1)" size="30"></u-icon>
					</view>
				</view>
			</view>
		</u-navbar>

		<view class="content-wrapper" :style="{height: contentHeight + 'px'}">
			<view class="line"></view>
			<view class="content-box">
				<scroll-view class="scroll-content" scroll-y="true">
					<view class="provinceList" v-for="(prvItem,index) in provinceList" :key="index"
						@click="selectProvince(index,prvItem)" :class="{active: currentIndex === index}">
						<view class="provinceList-name">
							{{ prvItem.regionName }}
						</view>
					</view>
					<view class="scroll-placeholder"></view>
				</scroll-view>
				<scroll-view class="cityContent" scroll-y="true">
					<view class="recommend">
						<!-- 推荐页面 (currentIndex == 0) -->
						<view v-show="currentIndex == 0">
							<view class="recommend_header">
								<view class="recommend_header-left">
									<view class="recommend_header-left-title">
										当前城市
									</view>
									<view class="recommend_header-left-value">
										{{currentCity}}
									</view>
								</view>
								<view class="recommend_header-right">
									<view class="recommend_header-right-title">
										刷新定位
									</view>
									<view class="recommend_header-right-value">
										<u-icon color="rgba(254, 119, 46, 1)" name="reload"></u-icon>
									</view>
								</view>
							</view>

							<view class="history" v-show="historyList.length >0">
								<view class="history-title">
									历史浏览
								</view>
								<view class="history-value">
									<view class="cityName" v-for="(historyItem,index) in historyList" :key="index"
										@click="selectCity(historyItem)">
										{{historyItem.shortName}}
									</view>
								</view>
							</view>
						</view>

						<!-- 城市列表页面 (currentIndex != 0) -->
						<view class="cityList" :class="{ 'mt-zero': currentIndex !== 0 }">
							<view class="cityList-title" v-show="currentIndex == 0">
								已开通城市
							</view>
							<view class="cityList-value" :class="{ 'mt-small': currentIndex !== 0 }">
								<view class="cityBox" v-for="(cityItem,index) in cityList" :key="index"
									@click="selectCity(cityItem)">
									<image class="cityBox-image"
										:src="currentIndex == 0 ? cityItem.imageUrl : (cityItem.imageUrl + '?imageView2/1/w/80/q/50')"
										mode="aspectFill" :lazy-load="currentIndex == 0">
									</image>
									<view class="cityBox-name">
										{{cityItem.shortName}}
									</view>
								</view>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</view>

		<commonSelectCity :show="showCommonSelectCity" @close="showCommonSelectCity = false" />
	</view>
</template>

<script>
	import commonSelectCity from '@/components/common-selectCity/common-selectCity.vue';
	import {
		getCityList,
		getRegionByHistoy,
		addRegionUserHistoy
	} from '@/request/api.js';
	export default {
		components: {
			commonSelectCity
		},
		data() {
			return {
				navbarHeight: 0, // navbar高度
				navbarTop: 0, // navbar距离顶部距离
				contentHeight: 0, // 内容区域高度
				currentIndex: 0, // 当前选中项索引
				provinceList: [{
					regionName: '推荐'
				}],
				historyList: [],
				currentCity: '定位失败',
				cityList: [],
				showCommonSelectCity: false

			}
		},
		onReady() {
			// 页面渲染完成后获取元素信息
			this.getNavbarInfo();
		},
		onLoad() {
			// 初始化当前城市
			this.refresh()
			// 获取省列表
			this.getPriviceList({})
			// 获取推荐tabs下的所有已开通城市
			this.getCity({
				isOpen: 1,
				level: 2
			})
			// 获取历史浏览记录
			this.getOldCityList()
		},
		methods: {
			// 新增历史记录（点击某个城市后调用）
			addNewHistoryCity(item) {
				let cityInfo = {
					regionId: item.regionId,
					userId: this.$store.state.userInfo.userId,
				}
				addRegionUserHistoy(cityInfo).then(res => {
					console.log('新增成功--城市选择历史记录');
				})
			},
			// 点击某个城市
			selectCity(item) {
				let cityInfo = {
					code: item.regionId,
					name: item.regionName
				}
				this.$store.commit('setCityInfo', cityInfo);
				this.addNewHistoryCity(item)
				uni.navigateBack()
			},
			// 获取历史浏览记录
			getOldCityList() {
				let params = {
					userId: this.$store.state.userInfo.userId,
				}
				getRegionByHistoy(params).then(res => {
					this.historyList = res.data.data
					console.log(res.data);
				})
			},
			goBack() {
				uni.navigateBack()
			},
			getPriviceList() {
				let params = {
					isOpen: 1,
					level: 1
				}
				getCityList(params).then(res => {
					this.provinceList = [...this.provinceList, ...res.data.rows]
				})
			},
			getCity(params) {
				getCityList(params).then(res => {
					this.cityList = res.data.rows
				})
			},
			getNavbarInfo() {
				const query = uni.createSelectorQuery().in(this);
				query.select('#navbar').boundingClientRect(data => {
					if (data) {
						// 获取系统信息
						const systemInfo = uni.getSystemInfoSync();
						// 计算内容区域高度（窗口高度 - navbar高度 - navbar距离顶部的距离）
						this.contentHeight = systemInfo.windowHeight - data.height - data.top;
					}
				}).exec();
			},
			selectProvince(index, item) {
				this.currentIndex = index;
				// 可以在这里添加其他逻辑，如加载对应的城市数据等
				let params = {}
				if (index == 0) {
					params.isOpen = 1
					params.level = 2
				} else {
					params.isOpen = 1
					params.parentId = item.regionId
				}

				this.getCity(params)
			},
			async refresh() {
				// 直接尝试获取位置
				uni.getLocation({
					type: 'gcj02',
					geocode: true,
					success: (data) => {
						uni.hideLoading();
						if (data.address) {
							this.currentProvince = data.address.province || '';
							this.currentCity = data.address.city || '';
							if (!this.currentCity && data.address.district) {
								this.currentCity = data.address.district;
							}
						} else {
							this.currentProvince = '';
							this.currentCity = '未知';
						}
					},
					fail: (err) => {
						// 根据错误信息判断是否是权限问题
						const errMsg = err.errMsg || err.message || '';
						const errCode = err.errCode || err.code || 0;

						// 判断是否为权限相关错误
						const isPermissionError =
							errCode === 1 || // 缺少定位权限
							errMsg.includes('缺少定位权限') ||
							errMsg.includes('定位服务没有开启') ||
							errMsg.includes('geolocation:12') ||
							errMsg.includes('authorization') ||
							errMsg.includes('permission');

						if (isPermissionError) {
							// 权限相关错误
							uni.showModal({
								title: '授权提示',
								content: '需要获取您的位置信息，请在设置中开启定位权限',
								showCancel: true,
							});
						} else {
							uni.showToast({
								title: '定位失败',
								icon: 'none'
							});
						}

						this.currentProvince = '';
						this.currentCity = '定位失败';
					}
				});
			},

		},
	}
</script>

<style lang="scss" scoped>
	.page {
		box-sizing: border-box;
		height: 100vh; // 固定页面高度
		display: flex;
		flex-direction: column;

		.closeImg {
			display: flex;
			align-items: center;
			width: calc(100vw - 60rpx); // 保持这个计算，因为左右各30rpx边距
			height: 80rpx;
			margin-right: 30rpx; // 添加左右边距，距离屏幕边缘30rpx

			image {
				width: 40rpx;
				height: 40rpx;
				flex-shrink: 0;
				margin-right: 30rpx;
			}

			.search-box {
				width: calc(100vw - 130rpx);
				display: flex;
				justify-content: space-between;
				height: 80rpx;
				align-items: center;
				background-color: rgba(243, 242, 242, 1);
				border-radius: 40rpx;

				.placeholder-content {
					color: rgba(77, 77, 86, 1);
					font-size: 28rpx;
					padding: 0 10rpx 0 20rpx;
					white-space: nowrap;
					overflow: hidden;
					text-overflow: clip;
				}

				.icon {
					padding-right: 30rpx;
				}
			}
		}

		.line {
			margin-top: 30rpx;
			height: 2rpx;
			background-color: rgba(41, 41, 48, 0.05);
		}

		.content-wrapper {
			flex: 1; // 占据剩余空间
			overflow: hidden; // 隐藏溢出内容

			.content-box {
				display: flex;
				height: 100%; // 滚动区域占满容器

				.scroll-content {
					width: 150rpx;
					height: 100%; // 滚动区域占满容器
					border-right: 1px solid rgba(41, 41, 48, 0.05);
					padding-bottom: 90rpx; // 与列表项高度一致

					.provinceList {
						.provinceList-name {
							line-height: 90rpx;
							text-align: center;
							font-weight: 400;
							font-size: 30rpx;
							transition: all 0.3s ease;
						}

						&:not(.active) .provinceList-name {
							color: rgba(0, 0, 0, 1);
						}
					}

					.provinceList.active {
						.provinceList-name {
							color: rgba(254, 119, 46, 1);
							font-weight: 900;
						}
					}

					// 占位元素样式
					.scroll-placeholder {
						height: 90rpx;
						width: 100%;
					}
				}

				.cityContent {
					width: calc(100vw - 212rpx);
					padding: 0 30rpx;

					.recommend {
						.recommend_header {
							display: flex;
							justify-content: space-between;
							padding-top: 30rpx;

							.recommend_header-left {
								display: flex;

								.recommend_header-left-title {
									color: rgba(0, 0, 0, 1);
									font-weight: bold;
									font-size: 30rpx;
									line-height: 30rpx;

								}

								.recommend_header-left-value {
									font-size: 30rpx;
									line-height: 30rpx;
									padding-left: 30rpx;
									color: rgba(254, 119, 46, 1);
								}
							}

							.recommend_header-right {
								display: flex;

								.recommend_header-right-title {
									color: rgba(254, 119, 46, 1);
									font-weight: 400;
									font-size: 26rpx;
									line-height: 30rpx;

								}

								.recommend_header-right-value {
									font-size: 30rpx;
									line-height: 30rpx;
									padding-left: 30rpx;
									color: rgba(254, 119, 46, 1);
								}
							}
						}
					}

					.history {
						margin-top: 50rpx;

						.history-title {
							font-weight: bold;
							font-size: 30rpx;
							color: rgba(0, 0, 0, 1);
							line-height: 30rpx;
						}

						.history-value {
							display: flex;
							flex-wrap: wrap; // 允许换行
							font-size: 26rpx;
							margin-top: 40rpx;

							.cityName {
								width: calc((100% - 60rpx) / 3); // 固定每个item占据1/3宽度
								height: 50rpx;
								background-color: rgba(243, 242, 242, 1);
								border-radius: 20rpx;
								line-height: 50rpx;
								text-align: center;
								margin-right: 30rpx; // 右间距
								margin-bottom: 20rpx; // 底部间距
								white-space: nowrap; // 不换行
								overflow: hidden; // 超出隐藏
								text-overflow: clip; // 裁剪文本，不显示省略号
								box-sizing: border-box; // 包含padding在内的盒模型

								// 每行第三个元素取消右边距
								&:nth-child(3n) {
									margin-right: 0;
								}
							}

							// 限制最多显示两行(6个元素)
							.cityName:nth-child(n+7) {
								display: none;
							}
						}
					}

					.cityList {
						margin-top: 50rpx;

						&.mt-zero {
							margin-top: 0;
						}

						.cityList-title {
							font-weight: bold;
							font-size: 30rpx;
							color: rgba(0, 0, 0, 1);
							line-height: 30rpx;
						}

						.cityList-value {
							display: flex;
							flex-wrap: wrap;
							gap: 30rpx;
							margin-top: 40rpx;

							&.mt-small {
								margin-top: 30rpx;
							}

							.cityBox {
								width: calc((100% - 60rpx) / 3);
								height: 160rpx;
								border-radius: 20rpx;
								position: relative;
								overflow: hidden;

								.cityBox-image {
									width: 100%;
									height: 100%;
								}

								.cityBox-name {
									position: absolute;
									bottom: 0;
									left: 0;
									right: 0;
									margin-top: 0;
									font-size: 30rpx;
									color: #fff;
									height: 72rpx;
									line-height: 72rpx;
									font-weight: 500;
									text-align: center;
									background: linear-gradient(to top, rgba(0, 0, 0, 0.5), transparent);
									text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
								}
							}
						}
					}
				}
			}
		}
	}
</style>